package org.gp.core.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.gp.core.entity.TokenModel;
import org.gp.core.service.TokenManager;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by Intellij IDEA
 * USER: luoliang
 * DATE: 2017/4/30
 * TIME: 下午10:42
 */
@Service
@Slf4j
public class RedisTokenManager implements TokenManager {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String createToken(String id) {
        String token = UUID.randomUUID().toString().replace("-", "");
        stringRedisTemplate.opsForValue().set(id, token);

        return token;
    }

    @Override
    public boolean checkToken(TokenModel tokenModel) {
        if (tokenModel == null) {
            return false;
        }
        String token = stringRedisTemplate.opsForValue().get(tokenModel.getId());
        if (StringUtils.isEmpty(token) || !Objects.equals(token, tokenModel.getToken())) {
            log.error("token={}不存在，用户验证不通过", tokenModel.getId());
            return false;
        }
        stringRedisTemplate.expire(tokenModel.getId(), 30, TimeUnit.MINUTES);

        return true;
    }

    @Override
    public void deleteToken(String id) {
        stringRedisTemplate.delete(id);
    }
}
